var notifier = {};

notifier.prefs = {};
notifier.prefs.baseUrl  = '';
notifier.prefs.username = '';
notifier.prefs.password = '';

notifier.actions = {};
notifier.actions.login = function() {
	$('#login input:submit').attr('disabled', 'true');
    notifier.prefs.username = $('#name').val();
    notifier.prefs.password = $('#pwd').val();
    notifier.api.doRequest('users/'+notifier.prefs.username+'.json', {
        success: function() {
            $('#login input:submit').removeAttr('disabled');
            $('#login').hide();
            $('#main').show();
            notifier.actions.refreshFriendsTimeline();
        },
        error: function(error, status) {
            $('#login input:submit').removeAttr('disabled');
            if (status == 401) {
                alert("Accès refusé !");
            } else {
                notifier.api.alertError(error, status);
            }
            $('#pwd').val('');
        }
    });
}
notifier.actions.register = function() {
    var data = {
        'user[name]': $('#reg_name').val(),
        'user[email]': $('#reg_email').val(),
        'user[pwd]': $('#reg_pwd').val()
    };
    notifier.api.doRequest('users.json', {
        method: 'POST',
        authenticate: false,
        params: data,
        success: function() {
            $('#register input:not(:submit)').val('');
            $('#register').hide();
            $('#login').show();
        },
        error: function(error, status) {
            if (status == 409) {
                alert("Ce nom d'utilisateur est déjà pris !");
            } else {
                notifier.api.alertError(error, status);
            }
        }
    });
}
notifier.actions.refreshFriendsTimeline = function() {
    notifier.api.doRequest('users/'+notifier.prefs.username+'/timeline.json', {
        success: function(notes) {
            $('#friends-timeline').empty();
            if (notes.length == 0) {
                $('#friends-timeline').append('<p class="empty">Rien pour l\'instant</p>');
            } else {
                for (var i in notes) {
                    $('#friends-timeline').append(notifier.ui.htmlForNote(notes[i]));
                }
                notifier.ui.bindNotesControls('friends-timeline');
            }
        }
    });
}
notifier.actions.sendNote = function() {
    text = $('#note_text').val();
    $('#note_submit').attr('disabled', 'true');
    notifier.api.doRequest('users/'+notifier.prefs.username+'/statuses.json', {
        method: 'POST',
        params: {'text': text},
        success: function(note) {
            $('#friends-timeline').prepend(notifier.ui.htmlForNote(note));
            notifier.ui.bindNotesControls('note_'+note.id);
            $('#note_text').val('');
            $('#note_submit').removeAttr('disabled');
        },
        error: function(error, status) {
            $('#note_submit').removeAttr('disabled');
            notifier.api.alertError(error, status);
        }
    });
}
notifier.actions.editNote = function(noteId) {
    var newText = $('#note_'+noteId+'_new_text').val();
    // hack pour Adobe AIR :
    // apparemment AIR envoie un body vide pour une requête PUT,
    // même lorsque l'on passe des params à l'objet XHR ;
    // on place donc les params dans la querystring
    notifier.api.doRequest('users/'+notifier.prefs.username+'/statuses/'+noteId+'.json?text='+newText, {
        method: 'PUT',
        //params: {'text': $('#note_'+noteId+'_new_text').val()},
        success: function(note) {
            $('#note_'+noteId+' p:first').text(note.text);
            notifier.ui.hideEditForm(noteId);
        }
    });
}
notifier.actions.deleteNote = function() {
    var noteId = notifier.ui.idFromElt(this.parentNode.parentNode, 'note');
    if (!confirm('Etes-vous sûr de vouloir supprimer cette note ?')) return;
    
    notifier.api.doRequest('users/'+notifier.prefs.username+'/statuses/'+noteId+'.json', {
        method: 'DELETE',
        success: function() {
            $('#note_'+noteId).remove();
        }
    });
}
notifier.actions.refreshFriendsList = function() {
    notifier.api.doRequest('users/'+notifier.prefs.username+'/friends.json', {
        success: function(friends) {
            $('#friends-list').empty();
            if (friends.length == 0) {
                $('#friends-list').append('<p class="empty">Aucun ami pour l\'instant</p>');
            } else {
                for (var i in friends) {
                    $('#friends-list').append(notifier.ui.htmlForFriend(friends[i]));
                }
                notifier.ui.bindFriendsControls('friends-list');
            }
        }
    });
}
notifier.actions.addFriend = function() {
    $('#friend_submit').attr('disabled', 'true');
    notifier.api.doRequest('users/'+notifier.prefs.username+'/friends.json', {
        method: 'POST',
        params: {'name': $('#friend_name').val()},
        success: function(friend) {
            $('#friends-list').prepend(notifier.ui.htmlForFriend(friend));
            notifier.ui.bindFriendsControls('friend_'+friend.id);
            $('#friend_name').val('');
            $('#friend_submit').removeAttr('disabled');
        },
        error: function(error, status) {
            $('#friend_submit').removeAttr('disabled');
            notifier.api.alertError(error, status);
        }
    });   
}
notifier.actions.removeFriend = function() {
    var friendId = notifier.ui.idFromElt(this.parentNode.parentNode, 'friend');
    notifier.api.doRequest('users/'+notifier.prefs.username+'/friends/'+friendId+'.json', {
        method: 'DELETE',
        success: function() {
            $('#friend_'+friendId).remove();
        }
    });
}
notifier.actions.addFavorite = function() {
    var noteId = notifier.ui.idFromElt(this.parentNode.parentNode, 'note');
    notifier.api.doRequest('users/'+notifier.prefs.username+'/favorites.json', {
        method: 'POST',
        params: {'status_id': noteId},
        success: function(fav) {
            var link = $('#note_'+noteId+' a:first');
            link.removeClass('not-favorite');
            link.addClass('favorite');
            link.unbind('click');
            link.click(notifier.actions.removeFavorite);
        }
    });
}
notifier.actions.removeFavorite = function() {
    var noteId = notifier.ui.idFromElt(this.parentNode.parentNode, 'note');
    notifier.api.doRequest('users/'+notifier.prefs.username+'/favorites/'+noteId+'.json', {
        method: 'DELETE',
        success: function() {
            var link = $('#note_'+noteId+' a:first');
            link.removeClass('favorite');
            link.addClass('not-favorite');
            link.unbind('click');
            link.click(notifier.actions.addFavorite);
        }
    });
}
notifier.actions.removeFavInList = function() {
    var noteId = notifier.ui.idFromElt(this.parentNode.parentNode, 'fav');
    notifier.api.doRequest('users/'+notifier.prefs.username+'/favorites/'+noteId+'.json', {
        method: 'DELETE',
        success: function() {
            $('#fav_'+noteId).remove();
        }
    });
}
notifier.actions.refreshFavoritesList = function() {
    notifier.api.doRequest('users/'+notifier.prefs.username+'/favorites.json', {
        success: function(favs) {
            $('#favorites-list').empty();
            if (favs.length == 0) {
                $('#favorites-list').append('<p class="empty">Aucun favori pour l\'instant</p>');
            } else {
                for (var i in favs) {
                    $('#favorites-list').append(notifier.ui.htmlForFav(favs[i]));
                }
                notifier.ui.bindFavsControls('favorites-list');
            }
        }
    });
}

notifier.ui = {};
notifier.ui.toggleLoading = function() {
    $('#loading').toggle();
}
notifier.ui.idFromElt = function(elt, type) {
	id = elt.id;
	return id.replace(new RegExp(type+'_', 'g'), '');
}
notifier.ui.showTab = function(tabLink, tabName) {
    $('a.active').removeClass('active');
    $(tabLink).addClass('active');
    $('div.tab:visible').hide();
    $('#'+tabName+'-tab').show();
}
notifier.ui.htmlForNote = function(note) {
    var html = '<div class="note" id="note_'+note.id+'">'
             +'<p class="note-text">'+note.text+'</p>'
             +'<p class="note-details">'+note.sender.name+' le '+note.timestamp
    if (note.sender.name == notifier.prefs.username) {
        html+= '&nbsp;<a href="#" class="note-edit">edit</a>';
        html+= '&nbsp;<a href="#" class="note-delete">delete</a>';
    } else {
        if (note.favorite_id != undefined) {
            var className = 'favorite';
        } else {
            var className = 'not-favorite';
        }
        html+= '&nbsp;<a href="#" class="'+className+'"></a>';
    }
    html+= '</p></div>';
    return html;
}
notifier.ui.htmlForFav = function(note) {
    return '<div class="note" id="fav_'+note.id+'">'
             +'<p class="note-text">'+note.text+'</p>'
             +'<p class="note-details">'+note.sender.name+' le '+note.timestamp
             +'&nbsp;<a href="#" class="favorite"></a>'
             +'</p></div>';
}
notifier.ui.bindFavsControls = function(eltId) {
    $('#'+eltId+' a.favorite').click(notifier.actions.removeFavInList);
}
notifier.ui.bindNotesControls = function(eltId) {
    $('#'+eltId+' a.note-edit').click(notifier.ui.createEditForm);
    $('#'+eltId+' a.note-delete').click(notifier.actions.deleteNote);
    $('#'+eltId+' a.favorite').click(notifier.actions.removeFavorite);
    $('#'+eltId+' a.not-favorite').click(notifier.actions.addFavorite);
}
notifier.ui.htmlForFriend = function(friend) {
    return '<div class="friend" id="friend_'+friend.id+'">'
            +'<span class="friend-avatar">?</span>'
            +'<p class="friend-name">'+friend.name+'</p>'
            +'<p class="friend-email">'+friend.email
            +'&nbsp;<a href="#" class="remove">remove</a>'
            +'</p>'
            +'</div>'
}
notifier.ui.bindFriendsControls = function(eltId) {
    $('#'+eltId+' a.remove').click(notifier.actions.removeFriend);
}
notifier.ui.createEditForm = function() {
    var noteId = notifier.ui.idFromElt(this.parentNode.parentNode, 'note');
    var form = document.createElement("form");
    form.id = 'edit_note_'+noteId;
    form.className = 'edit-form';
    form.onsubmit = function() { notifier.actions.editNote(noteId); return false; }

    var textArea = document.createElement("textarea");
    textArea.id = 'note_'+noteId+'_new_text';
    textArea.value = $('#note_'+noteId+' p:first').text();
    textArea.rows = 3;
    textArea.cols = 40;
    form.appendChild(textArea);

    var br = document.createElement("br");
    form.appendChild(br);
    
    var okButton = document.createElement("input");
    okButton.type = "submit";
    okButton.value = "Ok";
    form.appendChild(okButton);

    var cancelLink = document.createElement("a");
    cancelLink.href = "#";
    cancelLink.appendChild(document.createTextNode("annuler"));
    cancelLink.onclick = function() { notifier.ui.hideEditForm(noteId); }
    form.appendChild(cancelLink);
    
    $('#note_'+noteId).after(form);
    $('#note_'+noteId).hide();
}
notifier.ui.hideEditForm = function(noteId) {
    $('#note_'+noteId).show();
    $('#edit_note_'+noteId).remove();
}

notifier.api = {};
notifier.api.doRequest = function(url, options) {
    var defaults = {
        method: 'GET',
        params: {},
        authenticate: true,
        success: null,
        error: null
    };
    if (options == null) options = {};
    for (var index in defaults) {
        if (typeof options[index] == "undefined") options[index] = defaults[index];
    }

    var reqParams = {
        type: options.method,
        data: options.params,
        url: notifier.prefs.baseUrl + url,
        beforeSend: function(xhr) {
            notifier.ui.toggleLoading();
            if (options.authenticate) {
                xhr.setRequestHeader('Authorization', 'WSSE profile="UsernameToken"');
                xhr.setRequestHeader('X-WSSE', wsseHeader(notifier.prefs.username, notifier.prefs.password));
                //xhr.setRequestHeader("Cookie", "");
            }
            return xhr;
        },
        complete: function (xhr, status) {
            notifier.ui.toggleLoading();
        },
        success: function (responseText, status) {
            try {
                var data = eval('(' + responseText + ')');
            } catch (e) {
                var data = null;
            }
            if (options.success !== null) {
                options.success(data, status);
            }
        },
        error: function (xhr, status, error) {
            try {
                error = eval('(' + xhr.responseText + ')');
            } catch (e) {
                error = error;
            }
            if (options.error !== null) {
                options.error(error, xhr.status);
            } else {
                notifier.api.alertError(error, xhr.status);
            }
        }
    }
    return $.ajax(reqParams);           
}
notifier.api.alertError = function(error, status) {
    var str = "Erreur "+status+" !\n\n";
    if ('object' == typeof error) {
        for (var key in error) {
            str += key+': '+error[key]+"\n";
        }
    } else {
        str+= error;
    }
    alert(str);
}


